package com.ruoyi.common.utils;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;

/**
 * Created On : 2024/4/1.
 * Author : xuliang
 * Description: LastRowBackgroundHandler
 * <p>
 */
@Slf4j
public class SummaryBackgroundHandler implements RowWriteHandler {

    private IndexedColors backgroundColor;


    public SummaryBackgroundHandler(IndexedColors backgroundColor) {
        this.backgroundColor = backgroundColor;
    }

    @Override
    public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
        // Do nothing
    }

    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
        Sheet sheet = writeSheetHolder.getSheet();
        if(!isHead){
            if (relativeRowIndex.equals(0) || relativeRowIndex.equals(4) || relativeRowIndex.equals(12)) {
                log.info("relativeRowIndex：" + relativeRowIndex);
                CellStyle originalStyle = row.getCell(0).getCellStyle();
                CellStyle newStyle = createNewCellStyle(sheet.getWorkbook(), originalStyle);
                applyBackgroundColor(newStyle);
                applyBorderStyle(newStyle, originalStyle);

                for (Cell cell : row) {
                    cell.setCellStyle(newStyle);
                }
            }
        }

    }

    private CellStyle createNewCellStyle(Workbook workbook, CellStyle originalStyle) {
        CellStyle newStyle = workbook.createCellStyle();
        newStyle.cloneStyleFrom(originalStyle);
        return newStyle;
    }

    private void applyBackgroundColor(CellStyle style) {
        style.setFillForegroundColor(backgroundColor.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
    }

    private void applyBorderStyle(CellStyle newStyle, CellStyle originalStyle) {
        newStyle.setBorderTop(originalStyle.getBorderTop());
        newStyle.setBorderRight(originalStyle.getBorderRight());
        newStyle.setBorderBottom(originalStyle.getBorderBottom());
        newStyle.setBorderLeft(originalStyle.getBorderLeft());
    }

}



